package com.yuexinduo.mylibrary.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类描述：字符串工具类
 * 创建人：admin
 * 创建时间：2016/5/4 9:21
 * 修改人：admin
 * 修改时间：2016/5/4 9:21
 * 修改备注：
 */
public class StringUtil {

    /**
     * 字符串是否为空
     *
     * @param text ：要判断的字符串
     * @return ：是否为空
     */
    public static boolean isEmpty(String text) {
        return null == text || "".equals(text) || " ".equals(text) || "null".equals(text) || text.length() == 0;
    }

    /**
     * 是否是手机号码
     *
     * @return true是 false不是
     */
    public static boolean isTel(String str) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(14[[0-9]])|(17[0-9])||(15[0-9])|(16[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static boolean isAllNum(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static boolean isAllChar(String str) {
        return str.matches("^[a-zA-Z]*");
    }

    /**
     * 验证邮箱格式是否正确
     */
    public static boolean isEmail(String email) {
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return email.matches(regex);
    }

    /**
     * 比较图形验证码是相同
     *
     * @param code0
     * @param code1
     * @return
     */
    public static boolean isAuthCodeSame(String code0, String code1) {
        if (isEmpty(code0) || isEmpty(code1)) return false;
        String lowerCode0 = code0.toLowerCase();
        String lowerCode1 = code1.toLowerCase();
        return lowerCode0.equals(lowerCode1);
    }

    public static boolean isHuZhi(String s) {
        if (s.matches("\\d+(.\\d+)?")) {
            if (s.indexOf(".") > 0) {
                //System.out.println("浮点类型");
                return true;
            } else {
                // System.out.println("整形类型");
                return true;
            }
        } else {
            // System.out.println("不是数值类型");
            return false;
        }
    }

    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static Pattern IMG_URL = Pattern
            .compile(".*?(gif|jpeg|png|jpg|bmp)");

    private final static Pattern URL = Pattern
            .compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * binding.title.title.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
     *
     * @param second
     * @return
     * @Override public void onChronometerTick(Chronometer chronometer) {
     * second++;
     * chronometer.setText(FormatMiss(second));
     * }
     * });
     */

    public String FormatMiss(int second) {
        if (second == 0) {
            return "00:00:00";
        }
        String hh = second / 3600 > 9 ? second / 3600 + "" : "0" + second / 3600;
        String mm = (second % 3600) / 60 > 9 ? (second % 3600) / 60 + "" : "0" + (second % 3600) / 60;
        String ss = (second % 3600) % 60 > 9 ? (second % 3600) % 60 + "" : "0" + (second % 3600) % 60;
        return hh + ":" + mm + ":" + ss;
    }


    /**
     * 判断是否为一个合法的url地址
     *
     * @param str
     * @return
     */
    public static boolean isUrl(String str) {
        if (str == null || str.trim().length() == 0)
            return false;
        return URL.matcher(str).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 对象转DEBULE
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static double toDouble(String obj) {
        if (obj == null)
            return 0;
        return Double.parseDouble(obj);
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    public static String getString(String s) {
        return s == null ? "" : s;
    }


    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date(System.currentTimeMillis()));
    }

    /**
     * @param millis  要转化的日期毫秒数。
     * @param pattern 要转化为的字符串格式（如：yyyy-MM-dd HH:mm:ss）。
     * @return 返回日期字符串。
     */
    public static String millisToStringDate(long millis, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern,
                Locale.getDefault());
        return format.format(new Date(millis));
    }

    private static final long K = 1024;
    private static final long M = K * K;
    private static final long G = M * K;
    private static final long T = G * K;

    public static String bytesToHuman(final long value) {
        final long[] dividers = new long[]{T, G, M, K, 1};
        final String[] units = new String[]{"TB", "GB", "MB", "KB", "B"};
        if (value < 1)
            return 0 + " " + units[units.length - 1];
        String result = null;
        for (int i = 0; i < dividers.length; i++) {
            final long divider = dividers[i];
            if (value >= divider) {
                result = format(value, divider, units[i]);
                break;
            }
        }
        return result;
    }

    private static String format(final long value,
                                 final long divider,
                                 final String unit) {
        final double result =
                divider > 1 ? (double) value / (double) divider : (double) value;
        return new DecimalFormat("#.##").format(result) + " " + unit;
    }


    //时间搓转化天时分秒

    private String[] dayConvert(Long s) {
        String[] d = new String[4];
        long day = (s / 1000) / (3600 * 24);
        long hour = ((s / 1000) % (3600 * 24)) / 3600;
        long minu = (((s / 1000) % (3600 * 24)) / 3600) / 60;
        long second = ((((s / 1000) % (3600 * 24)) / 3600) / 60) / 60;
        d[0] = day + "";
        d[1] = hour + "";
        d[2] = minu + "";
        d[3] = second + "";
        return d;
    }

    public static int getRandomColor() {
        Random random = new Random();
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = 0; i < 2; i++) {
            //       result=result*10+random.nextInt(10);
            int temp = random.nextInt(16);
            r = r * 16 + temp;
            temp = random.nextInt(16);
            g = g * 16 + temp;
            temp = random.nextInt(16);
            b = b * 16 + temp;
        }
        return Color.rgb(r, g, b);
    }

    public static String getDateToString(long milSecond, String pattern) {
        Date date = new Date(milSecond);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static Boolean isZhiMu(String str) {
        if (str == null) return false;
        return str.matches("[a-zA-Z]+");
    }

    public static String getAppVersionName(Context context) {
        String versionName = "";
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public static boolean idCard(String text) {
        String regx = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex);
    }

    // 图片转 byte[] 数组
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static String spilt(String str){
        String[] split = str.split("\\.");
        String s = split[2];
        for (int i=0;i<s.length();i++){
            if(i==0){
              char c=  s.charAt(0);
              if((c+"").equals("0")){
                  s=s.charAt(1)+"";
              }
            }
        }
        return split[0]+"."+split[1]+"."+s;
    }
}
